package sample.web.beetl;

import java.io.File;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.carloha.finance.tool.PdfReport;
import com.carloha.finance.tool.PdfUtil;

/**
 * pdf报告
 * @author 草原狼
 *
 */
@RestController
@RequestMapping(value = "/carloha")
public class PdfReportController {
	static final Logger LOG = LoggerFactory.getLogger(PdfReportController.class);
	@Autowired
	private FileConfig fc;
	
	
	
	/**
	 * 上传文件。
	 * 
	 * @param file,
	 * 文件字节流， 其中filename是multipart中的变量名称
	 * @return
	 */
	@RequestMapping(value = "/excel/upload", method = RequestMethod.POST)
	@ResponseBody
	public void uploadFile(	
	@RequestHeader(value = "Content-Type") String type,		
			@RequestParam(value = "filename", required = true) MultipartFile file,HttpServletResponse response) {		
        String dir = getDir(fc.getDir());        
        String fileName = getFileName(file.getOriginalFilename());          
		try {			
			byte[] bytes = file.getBytes(); // 文件字节流			
			File fileToSave = new File(dir + "/" + fileName);
			FileCopyUtils.copy(bytes, fileToSave);
			//根据excel表格文件生成pdf报表
			PdfReport.createPdfReport(fileToSave.getPath());
			String pdfName = PdfReport.getReportFileName(fileToSave.getPath());
			LOG.info("pdf:"+pdfName);
			PdfUtil.download(response,pdfName);
		} catch (Exception ex) {
			ex.printStackTrace();			
		}
		
	}
	
	/**
	 * 构造文件路径
	 * 
	 * @return
	 */
	private String getDir(String dir) {		
		File savedir = new File(dir);
		// 如果文件夹不存在的话
		if (!savedir.exists()) {
			// 创建相应的文件夹
			savedir.mkdirs();
		}
		return dir;
	}
	
	/**
	 * 获取文件名
	 * @param fileName
	 * @return
	 */
	private String getFileName(String fileName) {		 
		return fileName;
	}
}
